#!/usr/bin/env python
# encoding: utf-8
"""
DGSNotifier.py

Copyright (c) 2007, Adrian Petrescu

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * The names of its contributors may not be used to endorse or promote
      products derived from this software without specific prior written
      permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""

from urllib import urlencode
from urllib2 import urlopen
from string import split
from string import strip
from Notifier import Notifier
from Notifier import LoginException
from Notifier import CookieNotSetException
from Notifier import ServerNotReachableException
from Game import GoGame

class DGSNotifier(Notifier):
   app_name = "Dragon Go Server"
   refresh_interval = 60
   userid = ""
   DGS_LOGIN_URL = "http://dragongoserver.net/login.php"
   DGS_STATUS_URL = "http://dragongoserver.net/quick_status.php"
   
   def getName(self):
      return self.app_name + " (" + self.getUserid() + ")"
   
   def setRefreshInterval(self, secs):
      self.refresh_interval = secs
   
   def getRefreshInterval(self):
      return self.refresh_interval
   
   def getUserid(self):
      return self.userid
            
   def setUserid(self, userid):
      self.userid = userid
      
   def getPasswd(self):
      return ""
   
   def setPasswd(self, passwd):
      pass
      
   def checkForGames(self):
      data = urlencode({'user' : self.getUserid()})
      try:
         status_out = urlopen(self.DGS_STATUS_URL + "?" + data).read()
         if status_out == '#Error: unknown_user\n':
            raise LoginException()
         if '#Warning: empty lists' in status_out:
            return []
         status_out = [strip(x) for x in split(status_out, "'G',") if (not ("#" in x))]
         status_out = [x for x in [split(x,",") for x in status_out]]
         status_out = [[strip(y, " '") for y in x] for x in status_out]
         game_list = [GoGame(self,x[0],x[1],x[2],x[3]) for x in status_out]
         return game_list
      except IOError:
         raise ServerNotReachableException()
   
   def checkLoginStatus(self):
      data = urlencode({'user' : self.getUserid()})
      try:
         handle = urlopen(self.DGS_STATUS_URL + "?" + data)
         if handle.read() == '#Error: unknown_user\n':
            return False
         else:
            return True
      except IOError:
         raise ServerNotReachableException()
   
   def login(self):
      if self.checkLoginStatus():
         return True
      else:
         return False
   
   def __init__(self, userid="Unknown"):
      self.userid=userid
      pass

if __name__ == '__main__':
   t = DGSNotifier()
   t.setUserid("AdrianP")
   print t.login()
   print t.checkLoginStatus()
   print t.checkForGames()
